package com.yyj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyj.common.JwtTokenUtils;
import com.yyj.dao.AdminDao;
import com.yyj.entity.Admin;
import com.yyj.entity.Params;
import com.yyj.exception.CustomException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    final
    AdminDao adminDao;

    public AdminService(AdminDao adminDao) {
        this.adminDao = adminDao;
    }

    public List<Admin> getAdmin() {
        return adminDao.getAdmin();
    }

    public PageInfo<Admin> getBySearch(Params params) {
        //开启分页查询
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        //裸数据 不包括数据总数,当前页和页面大小
        List<Admin> list = adminDao.getBySearch(params);
        //封装在一起的数据
        return PageInfo.of(list);
    }

    public void insertAdmin(Admin admin) {
        if (admin.getName() == null || admin.getName().isEmpty()) {
            throw new CustomException("用户名不能为空");
        }
        //添加管理员的重复性判断
        Admin addedAdmin = adminDao.selectByName(admin.getName());
        if (addedAdmin == null) {
            adminDao.insertAdmin(admin);
        } else {
            //已经有了，提示前台
            throw new CustomException("该用户名已经存在，请勿重复添加");
        }


    }

    public void updateAdmin(Admin admin) {
        adminDao.updateAdmin(admin);
    }


    public void delete(Integer id) {
        adminDao.deleteByPrimaryKey(id);
    }

    public Admin login(Admin admin) {
        //非空判断
        if (admin.getName() == null || admin.getName().isEmpty()) {
            throw new CustomException("用户名不能为空");
        }
        if (admin.getPassword() == null || admin.getPassword().isEmpty()) {
            throw new CustomException("密码不能为空");
        }

        Admin loginUser = adminDao.login(admin);
        if (loginUser == null) {
            throw new CustomException("用户名或密码错误");
        }
        //用户信息和token一起返回前台，生成一个token
        String token = JwtTokenUtils.genToken(loginUser.getId().toString(), loginUser.getPassword());
        loginUser.setToken(token);
        return loginUser;

    }

    public Admin findById(Integer id) {
        return adminDao.findById(id);
    }
}
